$(document).ready(function(){
	connect();
});

var rescueSocket;

function connect() {

    var host = window.location.host + "/rescueSocket";
    if ('WebSocket' in window) {
    	
    	var pl = location.protocol;
    	var socketProtocol;
    	if(pl == "https:"){
    	   console.log("protocol = " + pl);
    	   socketProtocol = "wss://";
    	} else {
    	   console.log("protocol = " + pl);
    	   socketProtocol = "ws://";
    	}
    	
    	rescueSocket = new WebSocket(socketProtocol + host);

    	rescueSocket.onopen = function (evnt) {
        };

        rescueSocket.onclose = function (evnt) {
            console.log('连接已关闭！');
        };

        rescueSocket.onmessage = function (evt) {
            var received_msg = JSON.parse(evt.data);
        	layer.alert("手机号码为" + received_msg.phone + "的用户发起了紧急求助", {
        		skin: 'layui-layer-lan',
        		closeBtn: 0,
        		anim: 4//动画类型
        	},function(index){
        		layer.close(index);
    			if(received_msg.lat != undefined && received_msg.lng != undefined) {
    				$("#tab_1").attr("src" , "/home?phone=" + received_msg.phone + "&lat=" + received_msg.lat + "&lng=" + received_msg.lng);
    				navTabs.find("a[data-id='1']").tab('show');
                }
        	});
        };
        rescueSocket.onerror = function (evnt) {
            console.log("webSocket Error");
        };
    } else {
        console.log('不支持 new WebSocket 方式连接！');
    }
}